package com.lst.api.config;


import com.lst.tools.basics.exception.BaseException;
import com.lst.tools.custom.constants.ErrorCodeConstants;
import com.lst.tools.custom.vo.JsonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
@ControllerAdvice("com.lst")
@ResponseBody
public class GlobalExceptionConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionConfig.class);

    @ExceptionHandler(BaseException.class)
    public JsonResponse<String> baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        String errorCode = ex.getErrorCode();
        String errorMessage = ex.getMessage();
        if (!ErrorCodeConstants.TOKEN_EXPIRE_ERROR.equals(errorCode)) {
            LOGGER.info(errorMessage, ex);
        }
        return JsonResponse.fail(errorCode, errorMessage);
    }

    @ExceptionHandler(Exception.class)
    public JsonResponse<String> otherExceptionHandler(HttpServletResponse response, Exception ex) {
        String errorMessage = ex.getMessage();
        LOGGER.error(errorMessage, ex);
        return JsonResponse.fail(ErrorCodeConstants.PUBLIC_ERROR, errorMessage);
    }
}
